# Title     : TODO
# Objective : TODO
# Created by: yz
# Created on: 2018/6/8
library(optparse)
library(magrittr)
library(tidyr)
library(tibble)
library(tidyverse)

option_list <- list(
  make_option("--t", type = 'character', action = "store", default = "Metabolite", help = "input metabolite ID type"),
  make_option("--d", type = 'character', action = "store", default = "./", help = "the database direcotry"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--config", default = "calculate_config.json", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

configJson <- fromJSON(opt$config)
fcMethod <- configJson$fcMethod

mSet <- InitDataObjects("conc", "pathora", FALSE)

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote"))

classNotes <- unique(sampleInfo$ClassNote)
groupNum <- length(classNotes)
print(groupNum)
fcData <- data.frame()
diffData <- read_csv("AllMet_with_Anno.csv")
if (groupNum == 2) {
  group1Name <- classNotes[1]
  group2Name <- classNotes[2]
  group1Sample <- sampleInfo %>%
    filter(ClassNote == group1Name) %>%
    .$SampleID
  group2Sample <- sampleInfo %>%
    filter(ClassNote == group2Name) %>%
    .$SampleID
  fcData <- read_csv("AllMet_with_Anno.csv") %>%
    rowwise() %>%
    do({
      result <- as.data.frame(.)
      group1Data <- result[group1Sample] %>% unlist
      group2Data <- result[group2Sample] %>% unlist
      mean1Name <- paste0(group1Name, ".Mean")
      result[, mean1Name] <- mean(group1Data)
      mean2Name <- paste0(group2Name, ".Mean")
      result[, mean2Name] = mean(group2Data)
      median1Name <- paste0(group1Name, ".Median")
      result[, median1Name] <- median(group1Data)
      median2Name <- paste0(group2Name, ".Median")
      result[, median2Name] = median(group2Data)
      result$FC <- my.fc(group1Data, group2Data, fcMethod)$fc
      result
    }) %>%
    ungroup() %>%
    mutate(log2FC = log(FC, 2)) %>%
    select(c("KEGG","HMDB", "log2FC")) %>%
    filter(!is.na(KEGG)) %>%
    mutate(col = ifelse(log2FC > 0, "red", "DeepSkyBlue")) %>%
    select(c("KEGG","HMDB", "col"))
}else {
  fcData <- diffData %>%
    select(c("KEGG","HMDB")) %>%
    filter(!is.na(KEGG)) %>%
    mutate(col = "gold")
}

fcData

write_tsv(fcData, "fc_color.txt")
head(fcData)

if (nrow(fcData) == 0) {
  quit(status = 0)
}

diffKeggs <- diffData %>%
  .$KEGG %>%
  map(function(x) {
    str_split(x, "/") %>% unlist()
  }) %>%
  flatten_chr()
diffKeggs


cmpd.vec <- diffKeggs
mSet <- Setup.MapData(mSet, cmpd.vec)
mSet <- CrossReferencing(mSet, "kegg", dataDir = opt$d)
mSet <- CreateMappingResultTable(mSet, dataDir = opt$d)
save(mSet, file = "idMapping_mSet.RData")

